package com.jbh.fourclibrary.fragment;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jbh.fourclibrary.R;
import com.jbh.fourclibrary.activity.PlayMp4Activity;
import com.jbh.fourclibrary.adapter.BaseRecyclerViewAdapter;
import com.jbh.fourclibrary.util.ConstantUtil;
import com.jbh.fourclibrary.util.Util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ColorFragment extends Fragment implements View.OnClickListener{

    private View view;
    private RecyclerView shapeRecyclerView;
    private ImageView im_color_1,im_color_2;
    private TextView tv_color1,tv_color2;
    private String color1="D";
    private int lastX;
    private int lastY;
    private int lastMX;
    private int lastMY;
    private ImageView im;
    private BaseRecyclerViewAdapter adapter;
    private VelocityTracker mVelocityTracker;
    private int selectPosition=0;
    private List<ColorBean> list=new ArrayList<>();


    View color_view;

    public ColorFragment() {

    }


    public static ColorFragment newInstance() {
        ColorFragment fragment = new ColorFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }




    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_color, container, false);
        initView(view);
        initData();
        initShapeList();
        touch();
        return view;
    }



    private void touch() {
        im.measure(0,0);
        im.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x= (int) event.getRawX();
                int y= (int) event.getRawY();
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        lastX = x;
                        lastY = y;
                        shapeRecyclerView.requestDisallowInterceptTouchEvent(true);
                        if (mVelocityTracker==null){
                            mVelocityTracker=VelocityTracker.obtain();
                        }else {
                            mVelocityTracker.clear();
                        }
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        mVelocityTracker.addMovement(event);
                        mVelocityTracker.computeCurrentVelocity(1000);
                        int mx=x-lastX;
                        int my=y-lastY;
                        im.setTranslationX(mx);
                        im.setTranslationY(my);
                        lastMX  = mx ;
                        lastMY  = my ;
                        Log.v("======m=====","mx="+mx+",my"+my);
                        return true;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        float t = ViewConfiguration.getTouchSlop();
                        if (Math.abs(lastMX)>t ||Math.abs(lastMY)>t ){
                            im.setVisibility(View.INVISIBLE);
                            ObjectAnimator.ofFloat(im,"TranslationX",lastMX , 0) .setDuration(300).start();
                            ObjectAnimator.ofFloat(im,"TranslationY",lastMY , 0) .setDuration(300).start();
                            shapeRecyclerView.requestDisallowInterceptTouchEvent(false);
                            if (lastMY<0){
                                if (lastMX < 0 ){
                                    im_color_1.setImageResource(ConstantUtil.get4CImgList2().get(color1));
                                    anim(im_color_1,0.8f);
                                    tv_color1.setText(color1);
                                }else {
                                    im_color_2.setImageResource(ConstantUtil.get4CImgList2().get(color1));
                                    anim(im_color_2,0.8f);
                                    tv_color2.setText(color1);
                                }
                            }
                        }
                        return true;
                }
                return false;
            }
        });
    }


    private void initView(View view) {
        tv_color1=view.findViewById(R.id.tv_color1);
        tv_color2=view.findViewById(R.id.tv_color2);
        im_color_1=view.findViewById(R.id.im_color_1);
        im_color_2=view.findViewById(R.id.im_color_2);
        im=view.findViewById(R.id.im);
        view.findViewById(R.id.onLeft).setOnClickListener(this);
        view.findViewById(R.id.onRight).setOnClickListener(this);
        shapeRecyclerView=view.findViewById(R.id.shapeRecyclerView);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        shapeRecyclerView.setLayoutManager(linearLayoutManager);
        view.findViewById(R.id.tv_play).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().startActivity(new Intent(getActivity(), PlayMp4Activity.class)
                        .putExtra("av_name","av_color"));
            }
        });
        measure();
    }

    private void measure() {
        int height =  Util.getHeight(getActivity()) - Util.getStatusBarHeight(getActivity())
                - Util.dpToPx(getActivity(),90);;
        color_view = view.findViewById(R.id.color_view);
        ViewGroup.LayoutParams params = color_view.getLayoutParams();
        params.height = height;

        View lay_content = view.findViewById(R.id.lay_content);
        params=lay_content.getLayoutParams();
        params.width = height+200;
    }

    private void initShapeList() {
        adapter=new BaseRecyclerViewAdapter(getActivity(),R.layout.item_color_imageview_layout,list.size()){

            @Override
            public void content(RecyclerView.ViewHolder holder, final int position) {
                super.content(holder, position);
                ViewGroup.LayoutParams param = holder.itemView.getLayoutParams();
                param .width = Util.dpToPx(getActivity(),90);


                final ColorBean shape = list.get(position);
                ImageView img_show=holder.itemView.findViewById(R.id.colorImg);
                img_show.setImageResource(shape.getColor());
                if (shape.isCheck()){
                    holder.itemView.setBackgroundResource(R.mipmap.icon_shape_press);
                }else {
                    holder.itemView.setBackgroundColor(Color.TRANSPARENT);
                }
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ColorBean l:list){
                            l.setCheck(false);
                        }
                        selectPosition = position ;
                        shape.setCheck(true);
                        notifyDataSetChanged();
                        color1 = shape.getName();
                        im.setImageResource(ConstantUtil.get4CImgList1().get(shape.getName()));
                        anim(im,1.3f);
                        im.setVisibility(View.VISIBLE);
                    }
                });
            }
        };
        shapeRecyclerView.setAdapter(adapter);
    }




    @RequiresApi(api = Build.VERSION_CODES.N)
    public void initData(){
        list.clear();
        HashMap<String, Integer> map = ConstantUtil.get4CImgList();
        Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<String, Integer> entry = it.next();
            ColorBean shapeBean=new ColorBean();
            if (entry.getKey().equals("D")){
                shapeBean.setCheck(true);
            }else {
                shapeBean.setCheck(false);
            }
            shapeBean.setName(entry.getKey());
            shapeBean.setColor(entry.getValue());
            list.add(shapeBean);
        }

        list.sort(new Comparator<ColorBean>() {
            @Override
            public int compare(ColorBean colorBean, ColorBean t1) {
                return colorBean.name.compareTo(t1.name);
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.onLeft) {
            onLeft();
        } else if (id == R.id.onRight) {
            onRight();
        }
    }




    /**
     *
     */
    public void onLeft(){
        if (selectPosition>0){
            selectPosition -- ;
            for (ColorBean l:list){
                l.setCheck(false);
            }
            color1 = list.get(selectPosition).getName() ;
            list.get(selectPosition).setCheck(true);
            if (adapter!=null)adapter.notifyDataSetChanged();
            shapeRecyclerView.scrollToPosition(selectPosition);
            im.setImageResource(ConstantUtil.get4CImgList1().get(list.get(selectPosition).getName()));
            anim(im,1.3f);
        }
    }


    /**
     *
     */
    public void onRight(){
        if (selectPosition<(list.size()-1)){
            selectPosition ++ ;
            for (ColorBean l:list){
                l.setCheck(false);
            }
            color1 = list.get(selectPosition).getName() ;
            list.get(selectPosition).setCheck(true);
            if (adapter!=null)adapter.notifyDataSetChanged();
            shapeRecyclerView.scrollToPosition(selectPosition);
            im.setImageResource(ConstantUtil.get4CImgList1().get(list.get(selectPosition).getName()));
            anim(im,1.3f);
        }
    }


    private void anim(View view,float f) {
        ObjectAnimator.ofFloat(view,"scaleX",1,f,1f).setDuration(200).start();
        ObjectAnimator.ofFloat(view,"scaleY",1,f,1f).setDuration(200).start();
    }


    class ColorBean{
        String name;
        int color;
        boolean isCheck;

        public int getColor() {
            return color;
        }

        public void setColor(int color) {
            this.color = color;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }


        public boolean isCheck() {
            return isCheck;
        }

        public void setCheck(boolean check) {
            isCheck = check;
        }
    }
}
